package com.zhixi.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhixi.common.R;
import com.zhixi.common.SharedVariablesCurrent;
import com.zhixi.pojo.Category;
import com.zhixi.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @ClassName CategoryController
 * @Author zhangzhixi
 * @Description 菜品及套餐分类
 * @Date 2022-7-10 13:39
 * @Version 1.0
 */
@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R<String> addCategory(HttpServletRequest request, @RequestBody Category category) {
        log.info("addCategory: {}", category);
        categoryService.save(category);
        return R.success("新增分类成功");
    }

    /**
     * 查询菜品及套餐分类
     *
     * @param page     分页对象
     * @param pageSize 每页显示的条数
     * @return R结果对象
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize) {
        log.info("page = {}, pageSize = {}", page, pageSize);
        Page<Category> pageInfo = new Page<>(page, pageSize);

        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort);
        categoryService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 修改菜品及套餐分类
     *
     * @param request  请求对象
     * @param category 分类对象
     * @return R结果对象
     */
    @PutMapping
    public R<String> updateCategory(HttpServletRequest request, @RequestBody Category category) {
        log.info("updateCategory: {}", category);
        categoryService.updateById(category);
        return R.success("修改分类成功");
    }

    /**
     * 删除菜品及套餐分类
     *
     * @param id 分类id
     * @return R结果对象
     */
    @DeleteMapping
    public R<String> deleteCategory(@RequestParam("ids") Long id) {
        log.info("deleteCategory: {}", id);
        categoryService.remove(id);
        return R.success("删除分类成功");
    }

    /**
     * 获取菜品分类下拉框数据
     *
     * @param category 类别对象
     * @return R结果对象
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();

        // SELECT id,type,name,sort,create_time,update_time,create_user,update_user FROM category WHERE (type = 1) ORDER BY sort ASC,update_time DESC
        queryWrapper.eq(category.getType() != null, Category::getType, category.getType());
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> categoryList = categoryService.list(queryWrapper);

        return R.success(categoryList);
    }
}













